package mi.payment.ui.query;

import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import mi.payment.R;
import mi.payment.transaction.sale.QRCodeQueryController;
import mi.payment.db.dao.PayDetail;
import mi.payment.ui.base.ParentActivity;
import mi.payment.transaction.ResultActivity;
import mi.payment.ui.print.FillInTheCertificateActivity;
import mi.payment.utils.MToast;
import mi.payment.utils.MoneyUtils;
import mi.payment.utils.NetUtils;
import mi.payment.utils.OrderJudgmentUtil;
import mi.payment.utils.SystemDateTime;
import mi.payment.utils.UIUtils;
import mi.payment.utils.transaction.CorrectTask;
import sunmi.sunmiui.title.Title;

/**
 * 交易查询
 *
 * @author Created by Administrator on 2017/9/7.
 */

public class TransactionDetailActivity extends ParentActivity {

    public static final String TRANSACTION_DETAIL = "transaction_detail";

    private Title title;
    private View dashedView, needCorrectView, correctSuccessView, correctFailView, cardNumberView, orderNumberView, thirdNumberView;
    private TextView transactionStatusTv, transactionTypeTv, transactionTimeTv, transactionAmountTv, printSearchView;
    private TextView certificateNumberTv, orderNumberTv, referenceNumberTv, cardNumberTv, thirdNumberTv;
    private PayDetail payDetail;
    private boolean isPrint, isRePrint;
    private int count = 5;

    private Handler handler = new Handler() {
        @Override

        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                findViewById(R.id.ic_back).setVisibility(View.GONE);
                printSearchView.setText(getString(R.string.print_ticket_count, count));
                count--;
                if (count == -1) {
                    printSearchView.setText(getString(R.string.print_ticket));
                    print();
                } else {
                    handler.sendEmptyMessageDelayed(0, 1000);
                }
            }
        }

    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_transaction_detail);
        initView();
        initData();
    }

    private void initView() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.colorBar));
        }
        findViewById(R.id.ic_back).setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                finish();
            }

        });
        dashedView = findViewById(R.id.dashed_line);
        /*不加就是实线*/
        dashedView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        needCorrectView = findViewById(R.id.need_correct_tips_layout);
        correctSuccessView = findViewById(R.id.correct_success);
        correctFailView = findViewById(R.id.correct_fail);
        printSearchView = (TextView) findViewById(R.id.print_or_search);
        /*二维码交易隐藏此控件*/
        cardNumberView = findViewById(R.id.card_number_layout);
        /*银行卡隐藏此控件*/
        orderNumberView = findViewById(R.id.order_number_layout);
        transactionStatusTv = (TextView) findViewById(R.id.transaction_status_tv);
        transactionTypeTv = (TextView) findViewById(R.id.transaction_type_tv);
        transactionTimeTv = (TextView) findViewById(R.id.transaction_time_tv);
        transactionAmountTv = (TextView) findViewById(R.id.transaction_amount_tv);
        certificateNumberTv = (TextView) findViewById(R.id.certificate_number_tv);
        orderNumberTv = (TextView) findViewById(R.id.order_number_tv);
        referenceNumberTv = (TextView) findViewById(R.id.reference_number_tv);
        cardNumberTv = (TextView) findViewById(R.id.card_number_tv);
        referenceNumberTv = (TextView) findViewById(R.id.reference_number_tv);
        thirdNumberView = findViewById(R.id.third_number_layout);
        thirdNumberTv = (TextView) findViewById(R.id.third_number_tv);

    }

    private void initData() {
        payDetail = (PayDetail) getIntent().getSerializableExtra(TRANSACTION_DETAIL);
        transactionTypeTv.setText(UIUtils.getTransactionTypeName(payDetail.transactionType));
        transactionAmountTv.setText(MoneyUtils.longCent2DoubleMoneyStr(payDetail.amount));
        transactionTimeTv.setText(SystemDateTime.getTimeByPayDetails(payDetail));
        certificateNumberTv.setText(payDetail.voucherNo);
        referenceNumberTv.setText(payDetail.referNo);
        transactionStatusTv.setTextColor(getResources().getColor(R.color.C333333));
        if (payDetail.transPlatform == 0) {//银行卡和银联钱包
            orderNumberView.setVisibility(View.GONE);
            cardNumberView.setVisibility(View.VISIBLE);
            cardNumberTv.setText(payDetail.CardNo);
            if ("00".equals(payDetail.tradeAnswerCode)) {//交易成功
                isRePrint = true;
                printSearchView.setVisibility(View.VISIBLE);
                if (payDetail.isCanceled) {//已撤销
                    transactionStatusTv.setText(R.string.revoked);
                } else if (payDetail.isReturnGood) {
                    transactionStatusTv.setText(R.string.transaction_success_return);
                } else {
                    transactionStatusTv.setText(R.string.transaction_success);
                }
                isPrint = true;
                if (payDetail.isNeedReversal) {//需要冲正
                    transactionStatusTv.setText(R.string.transaction_success_need_correct);
                    printSearchView.setVisibility(View.GONE);
                    needCorrectView.setVisibility(View.VISIBLE);
                }
                if (payDetail.isReversal) {//已冲正
                    if (CorrectTask.isCorrectSuccess(payDetail.correctAnswerCode)) {
                        transactionStatusTv.setText(R.string.transaction_success_correct_success);
                        printSearchView.setVisibility(View.GONE);
                        needCorrectView.setVisibility(View.GONE);
                        correctSuccessView.setVisibility(View.VISIBLE);
                    } else {
                        transactionStatusTv.setText(R.string.transaction_success_correct_fail);
                        printSearchView.setVisibility(View.GONE);
                        needCorrectView.setVisibility(View.GONE);
                        correctSuccessView.setVisibility(View.GONE);
                        correctFailView.setVisibility(View.VISIBLE);
                    }
                }
            } else {
                transactionStatusTv.setText(R.string.transaction_fail);
                if (payDetail.isNeedReversal) {//需要冲正
                    transactionStatusTv.setText(R.string.transaction_fail_need_correct);
                    printSearchView.setVisibility(View.GONE);
                    needCorrectView.setVisibility(View.VISIBLE);
                }
                if (payDetail.isReversal) {//已冲正
                    if (CorrectTask.isCorrectSuccess(payDetail.correctAnswerCode)) {
                        transactionStatusTv.setText(R.string.transaction_fail_correct_success);
                        printSearchView.setVisibility(View.GONE);
                        needCorrectView.setVisibility(View.GONE);
                        correctSuccessView.setVisibility(View.VISIBLE);
                    } else {
                        transactionStatusTv.setText(R.string.transaction_fail_correct_fail);
                        printSearchView.setVisibility(View.GONE);
                        needCorrectView.setVisibility(View.GONE);
                        correctFailView.setVisibility(View.VISIBLE);
                    }
                }
            }
        } else {//二维码类交易
            cardNumberView.setVisibility(View.GONE);
            orderNumberView.setVisibility(View.VISIBLE);
            orderNumberTv.setText(payDetail.thirdTransNum);
            if ("00".equals(payDetail.tradeAnswerCode) && 1 == payDetail.QRCodeTransState) {
                transactionStatusTv.setText(R.string.transaction_success);
                if (payDetail.isCanceled)
                    transactionStatusTv.setText(R.string.trade_cancle_success);
                if (payDetail.isReturnGood)
                    transactionStatusTv.setText(R.string.transaction_success_return);
                printSearchView.setVisibility(View.VISIBLE);
                isPrint = true;
                isRePrint = true;
            } else if (OrderJudgmentUtil.isQRUnknownOrder(payDetail)) {
                transactionStatusTv.setText(R.string.transaction_unknow);
                transactionStatusTv.setTextColor(getResources().getColor(R.color.colorBar));
                needCorrectView.setVisibility(View.GONE);
                printSearchView.setVisibility(View.VISIBLE);
                printSearchView.setText(R.string.query_immediately);
                isPrint = false;
            } else {
                transactionStatusTv.setText(R.string.transaction_fail);
            }
        }
        printSearchView.setOnClickListener(this);
        if (isPrint) {
            printSearchView.setText(R.string.print_ticket);
        }
        String customOrderNo = payDetail.customOrderNo;
        if (TextUtils.isEmpty(customOrderNo)) {
            thirdNumberView.setVisibility(View.GONE);
        } else {
            thirdNumberView.setVisibility(View.VISIBLE);
            thirdNumberTv.setText(customOrderNo);
        }
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.print_or_search:
                if (isPrint) {
                    // + 李少文；2018.1.4；點擊打印按鈕后不顯示記時UI(result界面會自動finish回到本界面)
                    printSearchView.setText(getString(R.string.print_ticket));
                    // - 李少文；2018.1.4；點擊打印按鈕后不顯示記時UI(result界面會自動finish回到本界面)
                    print();
                } else {
                    if (!NetUtils.isNetworkUsable(this)) {
                        MToast.showToast(R.string.toast_no_network_result);
                        return;
                    }
                    orderQuery();
                }
                break;
        }
    }

    private void updateStatus() {

    }

    private void print() {
        if (!isRePrint) {
            handler.removeMessages(0);
            count = 5;
            ResultActivity.startAction(mActivity, R.string.consume, payDetail);
        } else {
            FillInTheCertificateActivity.startAction(TransactionDetailActivity.this, payDetail.voucherNo + "");
        }
    }

    private void orderQuery() {
        // + 李少文；2018.1.4；查詢ctrl中會改變原paydetail中流水號??暫先查詢后恢復流水號
        final String originalVoucherNo = payDetail.getVoucherNo();
        // - 李少文；2018.1.4；查詢ctrl中會改變原paydetail中流水號??暫先查詢后恢復流水號
        QRCodeQueryController codeLastOrderQueryCtrl = new QRCodeQueryController(this, payDetail, new QRCodeQueryController.ResultCallback() {
            @Override
            public void queryComplete(PayDetail pay) {
                int qrCodeTransState = pay.getQRCodeTransState();
                String tradeAnswerCode = pay.getTradeAnswerCode();
                Log.e("ricardo", tradeAnswerCode + "---" + qrCodeTransState);

                payDetail.setVoucherNo(originalVoucherNo);
                payDetail.setQRCodeTransState(qrCodeTransState);
                payDetail.setTradeAnswerCode(tradeAnswerCode);
                payDetail.setTradeResultDes(pay.tradeResultDes);
                payDetail.setThirdTransNum(pay.thirdTransNum);
                //+ 李少文；2017/09/20；查询后更新数据库中的原订单的参考号和订单号
                payDetail.setThirdTransNum(pay.thirdTransNum);
                if (TextUtils.isEmpty(payDetail.getReferNo())) {
                    payDetail.setReferNo(pay.getReferNo());
                }
                //- 李少文；2017/09/20；查询后更新数据库中的原订单的参考号和订单号
                orderNumberTv.setText(pay.thirdTransNum);
                referenceNumberTv.setText(pay.referNo);
                if (qrCodeTransState == 1 && tradeAnswerCode.equals("00")) {
                    // 成功才更新数据
                    mPayDetailModel.update(payDetail);
                    isPrint = true;
                    isRePrint = false;
                    transactionStatusTv.setTextColor(getResources().getColor(R.color.C333333));
                    transactionStatusTv.setText(getString(R.string.transaction_success));
                    printSearchView.setText(getString(R.string.print_ticket_count, count));
                    count = 0;
                    handler.sendEmptyMessageDelayed(0, 0);
                    showToast(getString(R.string.order_unknown_hint));
                } else {
                    if (OrderJudgmentUtil.isQRUnknownOrder(pay)) {
                        showToast(getString(R.string.order_unknown_toast));
                    } else if (qrCodeTransState == -1) {
                        mPayDetailModel.update(payDetail);
                        transactionStatusTv.setTextColor(getResources().getColor(R.color.C333333));
                        transactionStatusTv.setText(getString(R.string.transaction_fail));
                        showToast(getString(R.string.order_fail_toast));
                        printSearchView.setVisibility(View.GONE);
                    } else {
                        String tradeResultDes = payDetail.getTradeResultDes();
                        if (!TextUtils.isEmpty(tradeResultDes)) {
                            transactionStatusTv.setText(tradeResultDes);
                            showToast(tradeResultDes);
                        } else {
                            showToast(getString(R.string.query_fail));
                        }
                    }
                }
            }

            @Override
            public void queryTimeout() {
                if (TransactionDetailActivity.this != null)
                    showToast(getString(R.string.order_unknown_timeout_toast));
            }
        });
        codeLastOrderQueryCtrl.queryLastQRCodeTrade();
    }

    @Override
    protected void onDestroy() {
        handler.removeCallbacksAndMessages(null);
        super.onDestroy();
    }
}
